package com.mercenary.wein.screenControl.ui.listener;

import com.mercenary.wein.screenControl.deviceControll.AndroidDevice;
import com.mercenary.wein.screenControl.ui.DeviceTable;
import com.mercenary.wein.screenControl.ui.inter.ChoosedDeviceInter;
import com.mercenary.wein.screenControl.ui.util.Constants;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class UploadListener implements ActionListener {
    private String action;
    private Component whereShow;
    private ExecutorService handlePool = Executors.newFixedThreadPool(30);
    private ChoosedDeviceInter deviceTable;
    public UploadListener(String action, Component whereShow, ChoosedDeviceInter deviceTable){
        this.action = action;
        this.whereShow = whereShow;
        this.deviceTable = deviceTable;
    }
    public void actionPerformed(ActionEvent e) {
        JFileChooser fc = new JFileChooser(Constants.RepertoryPath);
        fc.setDialogTitle("请选择要上传的文件...");
        fc.setApproveButtonText("确定");
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(whereShow)) {
            final String path=fc.getSelectedFile().getPath();
            if(action.equals("push")){
                final File file = new File(path);
                final String fileName = file.getName();
                for (final AndroidDevice ad:deviceTable.getChoosedADevices()){
                    handlePool.execute(new Runnable() {
                        public void run() {
                            ad.pushFile(file, Constants.DeviceFilePath+fileName);
                        }
                    });
                }
            }else if(action.equals("install")){
                for (final AndroidDevice ad:deviceTable.getChoosedADevices()){
                    handlePool.execute(new Runnable() {
                        public void run() {
                            ad.installAPK(path);
                        }
                    });
                }
            }
        }
    }

}